import pygame
import random

# 游戏窗口的大小
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 600

# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (128, 128, 128)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# 俄罗斯方块的形状
shapes = [
    [[1, 1, 1],
     [0, 1, 0]],
    [[0, 2, 2],
     [2, 2, 0]],
    [[3, 3, 0],
     [0, 3, 3]],
    [[4, 0, 0],
     [4, 4, 4]],
    [[0, 0, 5],
     [5, 5, 5]],
    [[6, 6],
     [6, 6]],
    [[7, 7, 7, 7]]
]

# 定义方块的大小
BLOCK_SIZE = 20

class Block:
    def __init__(self, x, y, shape):
        self.x = x
        self.y = y
        self.shape = shape

    def move_down(self):
        self.y += 1

    def move_left(self):
        self.x -= 1

    def move_right(self):
        self.x += 1

    def rotate(self):
        self.shape = [[self.shape[y][x]
                       for y in range(len(self.shape))]
                      for x in range(len(self.shape[0]) - 1, -1, -1)]

class Board:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.board = [[0 for _ in range(width)]
                      for _ in range(height)]

    def is_collision(self, block):
        for y, row in enumerate(block.shape):
            for x, cell in enumerate(row):
                if cell and self.board[y + block.y][x + block.x]:
                    return True
        return False

    def add_block(self, block):
        for y, row in enumerate(block.shape):
            for x, cell in enumerate(row):
                if cell:
                    self.board[y + block.y][x + block.x] = cell

    def remove_complete_rows(self):
        new_board = []
        num_complete_rows = 0
        for row in self.board:
            if 0 in row:
                new_board.append(row)
            else:
                num_complete_rows += 1
                new_row = [0 for _ in range(self.width)]
                new_board.insert(0, new_row)
        self.board = new_board
        return num_complete_rows

    def is_game_over(self):
        return any(self.board[0])

    def draw(self, surface):
        for y, row in enumerate(self.board):
            for x, cell in enumerate(row):
                if cell:
                    pygame.draw.rect(surface, GRAY,
                                     (x * BLOCK_SIZE,
                                      y * BLOCK_SIZE,
                                      BLOCK_SIZE, BLOCK_SIZE), 0)
                    pygame.draw.rect(surface, WHITE,
                                     (x * BLOCK_SIZE,
                                      y * BLOCK_SIZE,
                                      BLOCK_SIZE, BLOCK_SIZE), 1)


def draw_text(surface, text, font, color, x, y):
    text_obj = font.render(text, True, color)
    text_rect = text_obj.get_rect()
    text_rect.centerx = x
    text_rect.centery = y
    surface.blit(text_obj, text_rect)

def main():
    pygame.init()

    # 创建游戏窗口
    window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))

    # 设置游戏标题
    pygame.display.set_caption('俄罗斯方块')

    # 加载字体
    font = pygame.font.SysFont(None, 48)

    # 初始化游戏
    board = Board(WINDOW_WIDTH // BLOCK_SIZE, WINDOW_HEIGHT // BLOCK_SIZE - 1)
    current_block = Block(3, 0, random.choice(shapes))
    next_block = Block(3, 0, random.choice(shapes))
    clock = pygame.time.Clock()
    score = 0

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    current_block.move_left()
                    if board.is_collision(current_block):
                        current_block.move_right()

                elif event.key == pygame.K_RIGHT:
                    current_block.move_right()
                    if board.is_collision(current_block):
                        current_block.move_left()

                elif event.key == pygame.K_DOWN:
                    current_block.move_down()
                    if board.is_collision(current_block):
                        current_block.move_up()

                elif event.key == pygame.K_UP:
                    current_block.rotate()
                    if board.is_collision(current_block):
                        current_block.rotate()

        # 将方块向下移动
        current_block.move_down()

        # 如果方块碰到了底部或其他方块，则添加到游戏板上并生成新的方块
        if board.is_collision(current_block):
            current_block.move_up()
            board.add_block(current_block)
            num_complete_rows = board.remove_complete_rows()
            score += num_complete_rows * 10
            current_block = next_block
            next_block = Block(3, 0, random.choice(shapes))

            # 如果新方块与现有方块重叠，则游戏结束
            if board.is_collision(current_block):
                draw_text(window, 'GAME OVER', font, RED,
                          WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)
                pygame.display.update()
                pygame.time.wait(2000)
                pygame.quit()
                quit()

        # 将游戏板和方块绘制到屏幕上class Block:
    def __init__(self, x, y, shape):
        self.x = x
        self.y = y
        self.shape = shape
        self.color = COLORS[SHAPES.index(shape)]

    def move_down(self):
        self.y += 1

    def move_left(self):
        self.x -= 1

    def move_right(self):
        self.x += 1

    def rotate(self):
        self.shape = [[self.shape[y][x]
                       for y in range(len(self.shape))]
                      for x in range(len(self.shape[0]) - 1, -1, -1)]

    def draw(self, surface):
        for y, row in enumerate(self.shape):
            for x, cell in enumerate(row):
                if cell:
                    pygame.draw.rect(surface, self.color,
                                     (self.x * BLOCK_SIZE + x * BLOCK_SIZE,
                                      self.y * BLOCK_SIZE + y * BLOCK_SIZE,
                                      BLOCK_SIZE, BLOCK_SIZE), 0)
                    pygame.draw.rect(surface, WHITE,
                                     (self.x * BLOCK_SIZE + x * BLOCK_SIZE,
                                      self.y * BLOCK_SIZE + y * BLOCK_SIZE,
                                      BLOCK_SIZE, BLOCK_SIZE), 1)

        window.fill(BLACK)
        board.draw(window)
        current_block.draw(window)

        # 绘制下一个方块
        draw_text(window, 'NEXT:', font, WHITE, 400, 100)
        next_block.x = 12
        next_block.y = 3
        next_block.draw(window)

        # 绘制得分
        draw_text(window, 'SCORE:', font, WHITE, 400, 300)
        draw_text(window, str(score), font, WHITE, 400, 350)

        # 更新屏幕
        pygame.display.update()

        # 设置游戏帧率
        clock.tick(5)

if __name__ == '__main__':
    main()
